package cn.youwan.market.download;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.youwan.market.MyApplication;
import cn.youwan.market.R;
import cn.youwan.market.database.MyDao;
import cn.youwan.market.entity.DownFile;
import cn.youwan.market.entity.PromotionListbean;
import cn.youwan.market.entity.PromotionListbean.Appbean;
import cn.youwan.market.utils.Const;
import cn.youwan.market.utils.Utils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class AppDownloadService extends Service {
	private static Map<String, Appbean> downloadingApps;
	private DownloadTaskMgr downloadtaskMgr;
	private InstallAppReceiver installAppReceiver;
	private NotificationManager mNotificationManager;
	private Notification notification;
	private PendingIntent contentIntent;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		downloadingApps = Collections
				.synchronizedMap(new HashMap<String, Appbean>());
		downloadtaskMgr = DownloadTaskMgr.getInstance();

		installAppReceiver = new InstallAppReceiver();
		IntentFilter installFilter = new IntentFilter(
				Intent.ACTION_PACKAGE_ADDED);
		installFilter.addDataScheme("package");
		registerReceiver(installAppReceiver, installFilter);

		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		int icon = R.drawable.ic_launcher;
		CharSequence tickerText = "";
		
		//TODO 一个通知，并且点击可跳转到下载页面
		long when = System.currentTimeMillis();
		notification = new Notification(icon, tickerText, when);
//		Intent notificationIntent = new Intent(this, DownLoadingActivity.class);
//		contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
//				0);

	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		downloadingApps.clear();
		downloadingApps = null;
		downloadtaskMgr.cancelAllTask(this);
		downloadtaskMgr = null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent == null) {
			return super.onStartCommand(intent, flags, startId);
		}
		String action = intent.getAction();
		if (action.equals(Const.START_DOWNLOAD_ACTION)) {
			Log.v("yang", "进入下载");
			Appbean bean = (Appbean) intent.getSerializableExtra("bean");
			if (bean != null && !downloadingApps.containsKey(bean.getPkg())) {
				DownLoadThread task = new DownLoadThread(
						getApplicationContext(), bean);
				if (downloadtaskMgr.isCanStart()) {
					Log.v("yang", "开始下载");
					bean.setDownState(2);
					task.setDownState(1);
					task.start();
				} else {
					Log.v("yang", "等待下载");
					bean.setDownState(2);
					task.setDownState(0);
				}
				downloadingApps.put(bean.getPkg(), bean);
				downloadtaskMgr.addTask(bean.getPkg(), task);
				updateNotification();
				saveProgressApp(bean);
			} else {
				Log.v("yang", "下载对象为空");
			}
		} else if (action.equals(Const.DOWNLOADED_DOWNLOAD_ACTION)) {
			String pkgName = intent.getStringExtra("pkg");
			if (downloadingApps != null) {
				Appbean overDownloadApp = downloadingApps.get(pkgName);
				if (overDownloadApp != null) {
					overDownloadApp.setDownState(3);
				}
				//TODO 更新界面
//				sendMessage(AppDetailActivity.appDetailIntance,
//						DownLoadingActivity.downLoadingIntance,
//						PromotionActivity.PromotionIntance,
//						UpgradeActivity.UpgradeIntance,
//						GameCompetitiveActivity.GameComIntance,
//						GameRankActivity.GameRankIntance,
//						AppCompetitiveActivity.appComIntance,
//						AppRankActivity.appRankIntance,
//						CatoryDetailActivity.cataDetailIntance,
//						SpecialActivity.specialIntance,
//						SearchActivity.searchIntance, 2, pkgName);
				downloadtaskMgr.delTask(pkgName);
				updateDataBaseState(pkgName);
				downloadtaskMgr.hasNextTask();
				updateNotification();
				Utils.installApp(this, pkgName);
			}
		} else if (action.equals(Const.PAUSE_DOWNLOAD_ACTION)) {
			String pkgName = intent.getStringExtra("pkg");
			if (downloadingApps != null) {
				Appbean overDownloadApp = downloadingApps.get(pkgName);
				if (overDownloadApp != null) {
					overDownloadApp.setDownState(5);
				}
				downloadtaskMgr.delTask(pkgName);
				downloadingApps.remove(pkgName);
				downloadtaskMgr.hasNextTask();
				updateNotification();
				//TODO 更新界面
//				sendMessage(AppDetailActivity.appDetailIntance,
//						DownLoadingActivity.downLoadingIntance,
//						PromotionActivity.PromotionIntance,
//						UpgradeActivity.UpgradeIntance,
//						GameCompetitiveActivity.GameComIntance,
//						GameRankActivity.GameRankIntance,
//						AppCompetitiveActivity.appComIntance,
//						AppRankActivity.appRankIntance,
//						CatoryDetailActivity.cataDetailIntance,
//						SpecialActivity.specialIntance,
//						SearchActivity.searchIntance, 4, pkgName);
			}

		} else if (action.equals(Const.DELECT_DOWNLOAD_ACTION)) {
			String pkgName = intent.getStringExtra("pkg");
			if (downloadingApps != null) {
				Appbean overDownloadApp = downloadingApps.get(pkgName);
				if (overDownloadApp != null) {
					overDownloadApp.setDownState(6);
					downloadingApps.remove(pkgName);
				}
			}
			downloadtaskMgr.delTask(pkgName);
			downloadtaskMgr.hasNextTask();
			updateNotification();
			// 删除数据库中的信息和本地apk文件
			delectData(pkgName);
			//TODO 更新界面
//			sendMessage(AppDetailActivity.appDetailIntance,
//					DownLoadingActivity.downLoadingIntance,
//					PromotionActivity.PromotionIntance,
//					UpgradeActivity.UpgradeIntance,
//					GameCompetitiveActivity.GameComIntance,
//					GameRankActivity.GameRankIntance,
//					AppCompetitiveActivity.appComIntance,
//					AppRankActivity.appRankIntance,
//					CatoryDetailActivity.cataDetailIntance,
//					SpecialActivity.specialIntance,
//					SearchActivity.searchIntance, 5, pkgName);
		} else if (action.equals(Const.DELECTAPK_DOWNLOAD_ACTION)) {
			String pkgName = intent.getStringExtra("pkg");
			if (downloadingApps != null) {
				Appbean overDownloadApp = downloadingApps.get(pkgName);
				if (overDownloadApp != null) {
					overDownloadApp.setDownState(0);
					downloadingApps.remove(pkgName);
				}
			}
			//TODO 更新界面
//			sendMessage(null, null, PromotionActivity.PromotionIntance, null,
//					GameCompetitiveActivity.GameComIntance,
//					GameRankActivity.GameRankIntance,
//					AppCompetitiveActivity.appComIntance,
//					AppRankActivity.appRankIntance, null, null, null, 6,
//					pkgName);
		}

		/*
		 * else if (action.equals(Const.CONTIUE_DOWNLOAD_ACTION)) { String
		 * pkgName = intent.getStringExtra("pkg"); Appbean overDownloadApp =
		 * downloadingApps.get(pkgName); DownLoadThread task = new
		 * DownLoadThread(getApplicationContext(), overDownloadApp); if
		 * (downloadtaskMgr.isCanStart()) { Log.v("yang", "开始下载");
		 * overDownloadApp.setDownState(2); task.setDownState(1); task.start();
		 * } else { Log.v("yang", "等待下载"); overDownloadApp.setDownState(5);
		 * task.setDownState(0); }
		 * downloadtaskMgr.addTask(overDownloadApp.getPkg(), task); }
		 */
		return super.onStartCommand(intent, flags, startId);
	}

	class InstallAppReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getDataString() != null) {
				String pkgName = intent.getDataString().substring(
						intent.getDataString().indexOf(":") + 1);
				// 刷新已安装应用列表
				((MyApplication) getApplication()).refrashInstallApp();
				if (downloadingApps != null) {
					Appbean overDownloadApp = downloadingApps.get(pkgName);
					if (overDownloadApp != null) {
						overDownloadApp.setDownState(4);
						downloadingApps.remove(overDownloadApp.getPkg());
					}
					delectData(pkgName);
					//TODO 更新界面
//					sendMessage(AppDetailActivity.appDetailIntance, null,
//							PromotionActivity.PromotionIntance,
//							UpgradeActivity.UpgradeIntance,
//							GameCompetitiveActivity.GameComIntance,
//							GameRankActivity.GameRankIntance,
//							AppCompetitiveActivity.appComIntance,
//							AppRankActivity.appRankIntance,
//							CatoryDetailActivity.cataDetailIntance,
//							SpecialActivity.specialIntance,
//							SearchActivity.searchIntance, 3, pkgName);
				}
			}
		}
	}

	public static Map<String, Appbean> getDownloadingApps() {
		return downloadingApps;
	}

	// 安装完后删除数据库中的数据 并删除sd中的apk文件
	private void delectData(String pkg) {
		MyDao dao = new MyDao(this);
		dao.delete(pkg);
		File file = new File(Const.APKS + Utils.md5(pkg) + ".apk");
		if (file.exists()) {
			file.delete();
		}
	}

	// 下载完成后更改数据库中state的值为1
	private void updateDataBaseState(String pkg) {
		MyDao dao = new MyDao(this);
		dao.updateState(pkg, 1);
	}

	// 暂停保存到数据库 只保存一次
	private void saveProgressApp(Appbean bean) {
		MyDao dao = new MyDao(this);
		DownFile file = new DownFile();
		file.appId = bean.getId();
		file.company = bean.getAppCompany();
		file.name = bean.getAppName();
		file.rate = String.valueOf(bean.getRate());
		file.icon = bean.getAppIcon();
		file.fileSize = bean.getAppSize();
		file.url = bean.getUrl();
		file.pkg = bean.getPkg();
		file.state = 0;
		dao.insert(file);
	}

	// 更新通知栏
	private void updateNotification() {
		if (downloadingApps != null) {
			if (downloadingApps.size() != 0) {
				List<Appbean> lists = new ArrayList<PromotionListbean.Appbean>(
						downloadingApps.values());
				int index = 0;
				StringBuffer sb = new StringBuffer();
				for (Appbean bean : lists) {
					if (bean.getDownState() == 2 || bean.getDownState() == 5) {
						index++;
						sb.append(bean.getAppName() + " ");
					}
				}
				if (index != 0) {
					notification.setLatestEventInfo(this, index + "个下载任务",
							sb.toString(), contentIntent);
					mNotificationManager.notify(111, notification);
				} else {
					mNotificationManager.cancelAll();
				}
			} else {
				mNotificationManager.cancelAll();
			}
		}
	}

	
	//TODO 注掉了更新各个Activity视图的功能，等以后恢复
//	private void sendMessage(AppDetailActivity detail,
//			DownLoadingActivity loading, PromotionActivity promotion,
//			UpgradeActivity upgrade, GameCompetitiveActivity gameCom,
//			GameRankActivity gameRank, AppCompetitiveActivity appCom,
//			AppRankActivity appRank, CatoryDetailActivity catoryDetail,
//			SpecialActivity special, SearchActivity search, int what, String obj) {
//		if (detail != null) {
//			Message msg = new Message();
//			msg.what = what;
//			msg.obj = obj;
//			detail.btnHandler.sendMessage(msg);
//		}
//		if (loading != null) {
//			Message msg = new Message();
//			msg.what = what;
//			msg.obj = obj;
//			loading.btnHandler.sendMessage(msg);
//		}
//		if (promotion != null) {
//			Message msg = new Message();
//			msg.what = what;
//			msg.obj = obj;
//			promotion.btnHandler.sendMessage(msg);
//		}
//		if (upgrade != null) {
//			Message msg = new Message();
//			msg.what = what;
//			msg.obj = obj;
//			upgrade.btnHandler.sendMessage(msg);
//		}
//		if (gameCom != null) {
//			Message msg = new Message();
//			msg.what = what;
//			msg.obj = obj;
//			gameCom.btnHandler.sendMessage(msg);
//		}
//		if (gameRank != null) {
//			Message msg = new Message();
//			msg.what = what;
//			msg.obj = obj;
//			gameRank.btnHandler.sendMessage(msg);
//		}
//		if (appCom != null) {
//			Message msg = new Message();
//			msg.what = what;
//			msg.obj = obj;
//			appCom.btnHandler.sendMessage(msg);
//		}
//		if (appRank != null) {
//			Message msg = new Message();
//			msg.what = what;
//			msg.obj = obj;
//			appRank.btnHandler.sendMessage(msg);
//		}
//		if (catoryDetail != null) {
//			Message msg = new Message();
//			msg.what = what;
//			msg.obj = obj;
//			catoryDetail.btnHandler.sendMessage(msg);
//		}
//		if (special != null) {
//			Message msg = new Message();
//			msg.what = what;
//			msg.obj = obj;
//			special.btnHandler.sendMessage(msg);
//		}
//		if (search != null) {
//			Message msg = new Message();
//			msg.what = what;
//			msg.obj = obj;
//			search.btnHandler.sendMessage(msg);
//		}
//	}
}
